#coding:UTF-8 --
# app.py (略去部分代码，仅展示关键部分)

from flask import Flask, request, jsonify,render_template
import requests
from lxml import etree
from tqdm import tqdm  # 确保已安装tqdm库
import os
from datetime import datetime
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

requests.packages.urllib3.disable_warnings()
def getseat(precode,begin,to,count):
    list=[]
    for i in tqdm(range(begin,to+1)):
        id = str(i).rjust(count, '0')
        headers = {
            "Cookie": "Friends_where_frienddent_id=WechatTSG="+precode + id + "; Friends_where_friendname=WechatTSG=%e4%ba%8e%e6%b4%aa%e6%9c%8b; UserIdentID=WechatTSG=84E8365FA008B3F0B4BA945E8C595424; UserOpenID=WechatTSG=odsLhshCyIPTt9jdPoQHcXuUPT3M;"
        }
        url = 'https://libapp.hueb.edu.cn/Seat/friends/friendSeat.aspx'
        res = requests.get(url=url, verify=False, headers=headers)
        element = etree.HTML(res.content, parser=etree.HTMLParser(encoding='utf-8'))
        if (element.xpath("//title/text()")[0].strip() == "座位精灵"):
            obj=(precode+str(id),element.xpath("//input[@id='lblRoomName']/@value")[0],element.xpath("//input[@id='lblSeatNo']/@value")[0],element.xpath("//input[@id='lblBeginTime']/@value")[0])
            #print(" "+obj[0],end=' ')
            #print(obj[1], end=' ')
            #print(obj[2], end=' ')
            #print(obj[3])
            list.append(obj)
    return list
@app.route('/getseat', methods=['POST'])
def getseat_route():
    # 从请求中获取参数
    data = request.json
    precode = data['precode']
    begin = int(data['begin'])
    to = int(data['to'])
    count = int(data['count'])


    result_list=getseat(precode,begin,to,count)


    # 返回结果（这里应该返回JSON格式的结果）
    return jsonify(result_list)


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return 'No file part', 400

    file = request.files['file']

    if file.filename == '':
        return 'No selected file', 400

    # 生成时间戳（格式：YYYYMMDD_HHMMSS）
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')

    # 获取原始文件扩展名
    _, file_ext = os.path.splitext(file.filename)

    # 构造新文件名
    new_filename = f"{timestamp}{file_ext}"

    # 保存文件
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], new_filename)
    file.save(file_path)

    return f'File saved as {new_filename}', 200

# ...（其他路由和配置）
@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')
if __name__ == '__main__':
    ssl_certificate = 'cert.pem'  # 替换为您的证书路径
    ssl_key = 'key.pem'  # 替换为您的私钥路径
    # ssl_context = SSLContext(gevent.ssl.PROTOCOL_TLS)  # 使用 TLS 协议
    # ssl_context.load_cert_chain('./cert.pem', './key.pem')
 
    app.run(host="0.0.0.0",port=80)
    # server=pywsgi.WSGIServer(('0.0.0.0',443),app,ssl_context=ssl_context)
    # server.serve_forever()
